/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.qb9.flashlib.audio
{
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundLoaderContext;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;

	/**
	 * Simple class that delays sound loading
	 * until the first playback
	 */
	public class LazySound extends Sound
	{
		protected var stream  : URLRequest;
		protected var context:SoundLoaderContext;
		protected var started:Boolean;
		
		public function LazySound(stream:URLRequest = null, context:SoundLoaderContext = null)
		{
			super(stream, context);
		}
		
		public override function load(stream:URLRequest, context:SoundLoaderContext = null) : void
		{
			started = false;
			this.stream = stream;
			this.context = context;
		}
		
		public function forceLoad() : void
		{
			if (!started)
			{
				started = true;
				super.load(stream, context);
			}
		}
		
		public override function play(start:Number = 0, loops:int = 0, transf:SoundTransform=null) : SoundChannel
		{
			forceLoad();
			return super.play(start, loops, transf);
		}
		
		// The stream's url is more accurate
		public override function get url() : String
		{
			return stream ? stream.url : super.url;
		}
		
	}
}
